<template>
  <BasicModal v-bind="$attrs" @register="registerModal" :title="getTitle" @ok="handleSubmit" :canFullscreen="false" :minHeight="120" :height="120">
    <BasicForm @register="registerForm"/>
  </BasicModal>
</template>
<script lang="ts">
import {defineComponent, ref, computed, unref} from 'vue'
import {BasicModal, useModalInner} from '@/components/modal'
import {BasicForm, useForm} from '@/components/form/index'
import {formSchema} from '../data/data'
import {getDictTreeList,Api} from '../data/dict.api'

export default defineComponent({
  name: 'DictModal',
  components: {BasicModal, BasicForm},
  emits: ['success', 'register'],
  setup(_, {emit}) {
    const isUpdate = ref(true)

    const [registerForm, {resetFields, setFieldsValue, updateSchema, validate, saveOrUpdate},] = useForm({
      rowKey: 'dictId',
      saveApi: Api.save,
      updateApi: Api.edit,
      labelWidth: 100,
      schemas: formSchema,
      showActionButtonGroup: false,
    })

    const [registerModal, {setModalProps, closeModal}] = useModalInner(
        async (data) => {
          await resetFields()
          setModalProps({confirmLoading: false})
          isUpdate.value = !!data?.isUpdate
          if (unref(isUpdate)) {
            console.info("33333333333333",data.record);
            await setFieldsValue({
              ...data.record,
            })
          }
          const treeData = await getDictTreeList({})
          await updateSchema({
            field: 'parentDept',
            componentProps: {treeData},
          })
        },
    )

    const getTitle = computed(() =>
        !unref(isUpdate) ? '新增字典分类' : '编辑字典分类',
    )

    async function handleSubmit() {
      try {
        const values =  await saveOrUpdate();
        setModalProps({confirmLoading: true})
        closeModal()
        emit('success')
      } finally {
        setModalProps({confirmLoading: false})
      }
    }

    return {registerModal, registerForm, getTitle, handleSubmit}
  },
})
</script>
